package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.common.pojo.Item;
import com.hmall.item.service.IItemService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void updateStatus(Long id, Integer status) {
        this.update()
                .set("status", status)
                .eq("id", id)
                .update();

        // 发送消息，根据status判断routingkey
        String routingkey = status == 1 ? "item.up" : "item.down";
        rabbitTemplate.convertAndSend("item.topic", routingkey, id);
    }

    @Override
    @Transactional
    public void updateStockById(Long id, String type, Integer num) {
        try {
            String sql;
            if(StringUtils.equals("add",type)){
                sql = "stock = stock + " + num;
            }else{
                sql = "stock = stock - " + num;
            }
            this.update().setSql(sql).eq("id", id).update();
        } catch (Exception e) {
            throw new RuntimeException("扣减库存异常");
        }
    }
}
